package com.xxx.common.core.sampleframe;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class SFBeanUtils {


	public static <T> T   injectByJsonObject(T target,JSONObject jsonObject){
		Map<String,PropertyDescriptor> targetPDs = PropertyDescriptorUtils.getPDMaps(target.getClass());
		for (String key : jsonObject.keySet()) {
			try {
				if(targetPDs.containsKey(key)){
					PropertyDescriptor pd = targetPDs.get(key);
					pd.getWriteMethod().invoke(target, jsonObject.getObject(key,  pd.getPropertyType()));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}  
		}
		return target;
	}

	public static <T> T  injectByObject(T target,Object source){
		Map<String,PropertyDescriptor> targetPDs = PropertyDescriptorUtils.getPDMaps(target.getClass());
		Map<String,PropertyDescriptor> sourcePDs = PropertyDescriptorUtils.getPDMaps(source.getClass());
		PropertyDescriptor targetPD = null;
		PropertyDescriptor sourcePD = null;
		Method setMethod = null;
		Method getMethod = null;
		try {
			for (String targetKey: targetPDs.keySet()) {
				if(sourcePDs.containsKey(targetKey)){
					targetPD = targetPDs.get(targetKey);
					sourcePD = sourcePDs.get(targetKey);
					setMethod = targetPD.getWriteMethod();
					getMethod = sourcePD.getReadMethod();
					setMethod.invoke(target,getMethod.invoke(source));
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return target;
	}
	
}
